<?php

namespace App\Api\V1\Controllers;

use App\Models\Purse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;

/**
 * 用户中心
 * Class PurseController
 * @package App\Api\V1\Controllers
 */
class PurseController extends CommonController
{
    protected $purse = '';

    public function __construct()
    {
        parent::__construct();
        $this->getUserInfo();
        $this->purse = new Purse();
    }

    /**
     * 钱包列表
     * @return array
     */
    public function purseList()
    {
        $purse = $this->purse;
        $uid = $this->uid;
        $wallet = $purse->wallet($uid);
        $return = [];
        foreach ($wallet as $k => $v) {
            $return[] = $v;
        }
        return json_success('ok', $return,10000);
    }

    /**
     * 账户明细
     * type：1金额，2余额，3V币
     * @return array
     */
    public function detailList()
    {
        $purse_id = IT('purse_id',true);
        $page = IT('page') ?: 1;
        $rows = IT('rows') ?: 100;
        $page = ($page-1)*$rows;
        $type = IT('type') ?: 3;
        /*switch ($type) {
            case 1:// 金额明细
                $return = $this->moneyList($purse_id);
                break;
            case 2:// 余额明细
                $return = $this->cashList($purse_id);
                break;
            case 3:// E币明细
                $return = $this->ebList($purse_id);
        }*/
        $uid = $this->uid;

        // 查询条件
        $select = ['usertypeid','pursetypeid'];
        $where = array(
            ['id','=',$purse_id],
            ['pursetypeid','=',$type],
            ['status','=',1]
        );
        $purse_data = D('fund_user_purse')
            ->select($select)
            ->where($where)
            ->first();
        if (empty($purse_data)) {
            EE('参数有误', 0, 10032);
        }
        // 查询明细
        $return =  D('fund_transfer as t')
            ->select('t.id','t.outamount','t.intoamount','r.remarks','t.created_at','t.outpurseid','t.intopurseid')
            ->leftJoin('fund_transfer_reason as r','t.reasoncode','=','r.code')
            ->where([['t.outuserid','=',$uid],['t.outusertypeid','=',$purse_data->usertypeid],['t.outpursetypeid','=',$purse_data->pursetypeid],['t.outpurseid','=',$purse_id]])
            ->orWhere([['t.intouserid','=',$uid],['t.intousertypeid','=',$purse_data->usertypeid],['t.intopursetypeid','=',$purse_data->pursetypeid],['t.intopurseid','=',$purse_id]])
            ->offset($page)
            ->limit($rows)
            /*->toSql();*/
            ->get();
        foreach ($return as $k => $v) {
            if ($purse_id == $v->outpurseid) {
                $return[$k]->amount = -$v->outamount / 100;
            } else {
                $return[$k]->amount = $v->intoamount / 100;
            }
            unset($return[$k]->outamount);
            unset($return[$k]->intoamount);
            unset($return[$k]->outpurseid);
            unset($return[$k]->intopurseid);
        }
        return json_success('ok', $return, 10000);
    }

    /**
     * 转赠
     */
    public function donate()
    {
        $into_uid = IT('touid', true, "转赠给对方的微影号必须填写", 10105);
        $amount = IT('amount', true, "转赠v币数量必须填写", 10106) * 100;
//        $pay_password = IT('pay_password', true, "支付密码必须填写");//暂时不用
        $pay_password = "";
        $amount = floor($amount);//小数位数做舍去处理
        $usertypeid = 3;
        $pursetypeid = 3;
        $out_uid = $this->uid;
        $this->checkParm($out_uid, $into_uid, $amount, $pay_password, $usertypeid, $pursetypeid);
        DB::beginTransaction();
        $res_donate = $this->handleDataOfDonating($out_uid, $into_uid, $amount, $usertypeid, $pursetypeid);
        if (!$res_donate) {
            DB::rollBack();
            return json_error('操作失败', [], 10001);
        }
        $data = [
            'uid' => $into_uid,
            'amount' => $amount / 100, 
            'created_at' => time2date()
        ];
        DB::commit();
        return json_success('转赠成功', $data, 10107);
    }

    /**
     * 转赠功能的各类输入参数检测和判断
     * @param $out_uid  转赠发起人uid
     * @param $into_uid 转赠目标人uid
     * @param $amount   转赠V币数量
     * @param $pay_password 支付密码
     * @param $usertypeid
     * @param $pursetypeid
     */
    private function checkParm($out_uid, $into_uid, $amount, $pay_password, $usertypeid, $pursetypeid)
    {
        $out_balance = D('fund_user_purse')
            ->where(['uid' => $out_uid, 'usertypeid' => $usertypeid, 'pursetypeid' => $pursetypeid])
            ->value('balance');
        if($amount < 100){
            EE("转赠V币数量要不小于1", 0, 10108);
        }
        if($out_balance < $amount){
            EE("V币不足以转赠", 0, 10109);
        }
//        $pay_psword = D('users')
//            ->where(['id' => $out_uid])
//            ->value('pay_password');
//        $md5password = md5($pay_password);
//        if ($md5password != $pay_psword) {
//            EE('支付密码错误');
//        }
        $res_user = D("users")->where(['id' => $into_uid])->first();
        if(empty($res_user)){
            EE("该微影号不存在!", 0, 10110);
        }
        $res_purse = D('fund_user_purse')
            ->where(['uid' => $into_uid, 'usertypeid' => $usertypeid, 'pursetypeid' => $pursetypeid])
            ->first();
        if(empty($res_purse)){
            EE("该微影号的钱包不存在!", 0, 10111);
        }
    }

    /**
     * 处理转赠的各类数据,即是更新数据库操作
     * @param $out_uid  转赠发起人uid
     * @param $into_uid 转赠目标人uid
     * @param $amount   转赠V币数量
     * @param $usertypeid
     * @param $pursetypeid
     */
    private function handleDataOfDonating($out_uid, $into_uid, $amount, $usertypeid, $pursetypeid)
    {
        $where_out = [
            'uid' => $out_uid,
            'pursetypeid' => $pursetypeid
        ];
        $where_into = [
            'uid' => $into_uid,
            'pursetypeid' => $pursetypeid
        ];
        $res_out = D('fund_user_purse')
            ->where($where_out)
            ->decrement('balance', $amount);
        $res_into = D('fund_user_purse')
            ->where($where_into)
            ->increment('balance', $amount);
        $out_purse = D('fund_user_purse')
            ->where($where_out)
            ->first();
        $into_purse = D('fund_user_purse')
            ->where($where_into)
            ->first();
        $where_insert = [
            'reasoncode' => 10006,//转赠
            'outuserid' => $out_uid,
            'outusertypeid' => $usertypeid,
            'outpursetypeid' => $pursetypeid,
            'outpurseid' => $out_purse->id,
            'outamount' => $amount,
            'outbalance' => $out_purse->balance,
            'intouserid' => $into_uid,
            'intousertypeid' => $usertypeid,
            'intopursetypeid' => $pursetypeid,
            'intopurseid' => $into_purse->id,
            'intoamount' => $amount,
            'intobalance' => $into_purse->balance,
            'detail' => '转赠',
            'status' => 1,
            'remarks' => '',
            'created_at' => time2date(),
            'updated_at' => time2date()
        ];
        $res_insert = D('fund_transfer')
            ->insertGetId($where_insert);
        if (empty($res_out) || empty($res_into) || empty($res_insert)) {
            return false;
        }
        return true;
    }
    /**
     * 金额明细
     * @param $purse_id 钱包ID
     * @return mixed
     */
    protected function moneyList($purse_id)
    {
        return $purse_id;
    }

    /**
     * 余额明细
     * @param $purse_id 钱包ID
     * @return mixed
     */
    protected function cashList($purse_id)
    {
        return $purse_id;
    }

    /**
     * E币明细
     * @param $purse_id 钱包ID
     * @return mixed
     */
    protected function ebList($purse_id)
    {
        return $purse_id;
    }
}